package post

import (
	"context"
	"strconv"
	"strings"

	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckForumPostFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCheckForumPostFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckForumPostFavoriteLogic {
	return &CheckForumPostFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckForumPostFavoriteLogic) CheckForumPostFavorite(
	req *types.CheckForumPostFavoriteReq,
	headers *[]*types.Header,
) (*types.CheckForumPostFavoriteResp, error) {
	if req.PostId == nil || *req.PostId == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	if req.Type == nil || *req.Type == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_TYPE_INVALID)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	postId := strconv.FormatInt(int64(*req.PostId), 10)
	reactionType := util.GetForumReactionType(*req.Type)
	var filters []string
	filters = append(filters, "PostId,equalTo:"+postId)
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	filters = append(filters, "Type,equalTo:"+reactionType)

	var preFilters []string
	preFilters = append(preFilters, "PostId,equalTo:"+postId)
	preFilters = append(preFilters, "Type,equalTo:"+reactionType)

	res, err := l.svcCtx.ForumRpc.GetReactionLogList(l.ctx, &forumclient.BaseListReq{
		Preload:   pointy.GetPointer("forumReactionLog:PostId,Status,Count"),
		Filter:    pointy.GetPointer(strings.Join(filters, ";")),
		PreFilter: pointy.GetPointer(strings.Join(preFilters, ";")),
	})
	if err != nil {
		return nil, err
	}

	var status *uint32
	var count *uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Status != nil {
				status = v.Status
				break
			}
		}
	}
	if len(res.Extra) > 0 {
		for _, v := range res.Extra {
			if v.Count != nil {
				count = v.Count
				break
			}
		}
	}

	return &types.CheckForumPostFavoriteResp{
		Done:  status,
		Count: count,
	}, nil
}
